import list_behavior from "../../behavior/list_behavior";
import {goPay} from "../../service/order";
import goodsCartService from "../../service/goodsCart";
import {simplePost} from "../../utils/request";
import {showToastSuccess} from "../../utils/tool";

const app = getApp()
const global = app.globalData

Page({
    behaviors:[list_behavior],
    data: {
        nav: {
            title:"购物车"
        },
        imageUrl:global.imageUrl,
        info:{
            cartIdArr:[],
            amount:0,
        },
    },
    onLoad: function (options={}) {
        this.init(options)
    },
    goodsChange(e){
        const {value} = e.detail
        this.setData({
            [`info.cartIdArr`]:value,
        })
        this.computedAmount(value)
    },
    computedAmount(idArr){
        let amount = 0
        const {list} = this.data
        for (let id of idArr){
            const it = list.items.find(item => item.id == id)
            if (it){
                amount += it.goods_sku_id ? it.goods.sku.showPrice*100 : it.goods.showPrice*100
            }
        }
        this.setData({
            [`info.amount`]: parseFloat(amount/100)
        })
    },
    toPay(){
        const {info, list} = this.data
        const goodsUl = list.items.filter(item => {
            return info.cartIdArr.some(vo => vo == item.id)
        }).map(item => {
            return item.goods
        })
        if (goodsUl.length==0){
            return;
        }

        goPay({
            create_type:'cart',
            order_type:'normal',
            cart_ids: info.cartIdArr,
            goodsUl,
        })
    },
    // 删除无效的商品
    remove(e){
        const {index} = e.currentTarget.dataset
        const {list} = this.data
        const li = list.items[index]
        goodsCartService.add({
            goods_id: li.goods_id,
            goods_sku_id: li.goods_sku_id,
            num:0, // 数量为0，则删除数据
        }).then(r => {
            this.setData({
                [`list.items[${index}].remove`]:true,
            })

        })
    },
    allCheck(){
        const {list} = this.data
        const idArr = list.items.map(li => {
            return li.id
        })
        this.setData({
            [`info.cartIdArr`]:idArr,
        })
        this.computedAmount(idArr)
    },
    checkedRemove() {
        const {info} = this.data
        simplePost('/goodsCart/del', {ids: info.cartIdArr}).then(r => {
            // 重新加载列表
            this.setList(1)
            // 更新购物车商品数量
            app.globalData.cartNum = r.num
            showToastSuccess("操作成功")
        })

    },
    init(options){
        this.setData({
            [`list.url`]:"/goodsCart/paginate"
        })
        this.setList(1)
    }
});
